import json
# from datetime import date
from datetime import date

from django.contrib.auth import login
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import jwt_decode_handler

from person.models import User
from qa.models import Label, Question, Reply
from qa.serializers import LabelsSerializer, QuestionsSerializer, ReplyQuestionSerializer, LabelsDetailSerializer, \
    QuestionsPostSerializer, LabelFullSerializer


# 全, 单标签的问题
# 关注, 取消关注标签, 标签详情


class LabelsModelView(ModelViewSet):
    serializer_class = LabelsSerializer
    queryset = Label.objects.all()
    # permission_classes = [AllowAny]
    # 4.15 标签详情
    def retrieve(self, request, *args, **kwargs):
        id = kwargs['pk']
        label = Label.objects.get(id=id)
        serializer = LabelsDetailSerializer(label)
        return Response(serializer.data)


    # 4.2 用户关注的标签列表
    @action(methods=['get'], detail=False)
    # @method_decorator(ensure_csrf_cookie)
    def users(self, request, pk=None):
        # user_id = request.user.id
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        labels = user.labels.all()
        serializer = LabelsSerializer(labels, many=True)
        return Response(serializer.data)

    # 4.13 关注标签
    @action(methods=['put'], detail=True)
    def focusin(self, request, pk):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=pk)
        label.users.add(user)
        return Response({'message':'已关注', 'success':True})

    # 4.14 取消关注标签 todo
    @action(methods=['put'], detail=True)
    def focusout(self, request, pk):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        label = Label.objects.get(id=pk)
        label.users.remove(user)
        return Response({'message':'取消关注', 'success':True})

    # 隐藏任务, labels/full
    @action(methods=['get'], detail=False)
    def full(self, request):
        labels = Label.objects.all()
        serializer = LabelFullSerializer(labels, many=True)
        return Response(serializer.data)



# 新, 热, 待回答的问题
class QuestionsModelView(ModelViewSet):
    # 4.3最新回答的问题
    @action(methods=['get'], detail=False)
    def new(self, request, id=None):
        if id == '-1':
            questions = Question.objects.filter(reply__gt=0).order_by('-replytime')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.filter(reply__gt=0).order_by('-replytime')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)

    # 4.4热门回答的问题
    @action(methods=['get'], detail=False)
    def hot(self, request, id=None):
        if id == '-1':
            questions = Question.objects.filter(reply__gt=0).order_by('-reply')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.filter(reply__gt=0).order_by('-reply')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)

    # 4.5等待回答的问题
    @action(methods=['get'], detail=False)
    def wait(self, request, id=None):
        if id == '-1':
            questions = Question.objects.filter(reply=0).order_by('-createtime')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.filter(reply=0).order_by('-createtime')
            serializer = QuestionsPostSerializer(questions, many=True)
            return Response(serializer.data)


# 问题发布和详情, 问题有没有用
class QuestionsMessageModelView(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    serializer_class = QuestionsSerializer
    queryset = Question.objects.all()
    # 4.6发布问题
    def create(self, request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        data = request.data
        with transaction.atomic():
            save_id = transaction.savepoint()
            question = Question.objects.create(
                content=data['content'],
                title = data['title'],
                user_id=user_id
            )
            labels = data['labels']
            for i in labels:
                question.labels.add(i)
            transaction.savepoint_commit(save_id)
        return Response({'message':'发布成功', 'success':True})

    # 4.7 问题详情
    def retrieve(self, request, *args, **kwargs):
        question_id = self.kwargs['pk']
        question = Question.objects.get(id=question_id)
        question.visits = question.visits + 1
        question.save()
        serializer = QuestionsSerializer(question)
        return JsonResponse(serializer.data)


    # 4.8 问题有用
    @action(methods=['put'], detail=True)
    def useful(self, request, pk=None):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        reply = Reply.objects.filter(problem_id=pk).filter(user_id=user_id).filter(type=3).\
            filter(Q(useful_count__gt=0)|(Q(unuseful_count__gt=0)))
        if reply.exists():
            return Response({'message':'请不要重复操作', 'success':False})
        else:
            with transaction.atomic():
                save_id = transaction.savepoint()
                question = Question.objects.get(id=pk)
                question.useful_count = question.useful_count + 1
                question.save()
                reply = Reply.objects.create(
                    problem_id=pk,
                    user_id=user_id,
                    useful_count=1,
                    type=3
                )
                transaction.savepoint_commit(save_id)

            return Response({'message':'操作成功', 'success':True})
    # 4.9 问题没用
    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk=None):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        reply = Reply.objects.filter(problem_id=pk).filter(user_id=user_id).filter(type=3).\
            filter(Q(useful_count__gt=0)|(Q(unuseful_count__gt=0)))
        if reply.exists():
            return Response({'message': '请不要重复操作', 'success':False})
        else:
            with transaction.atomic():
                save_id = transaction.savepoint()
                question = Question.objects.get(id=pk)
                question.unuseful_count = question.unuseful_count + 1
                question.save()
                reply = Reply.objects.create(
                    problem_id=pk,
                    user_id=user_id,
                    unuseful_count=1,
                    type=3
                )
                transaction.savepoint_commit(save_id)
            return Response({'message': '操作成功', 'success':True})


# 回答问题, 回答有没有用
class ReplyModelView(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    # 4.10 回答问题
    def create(self, request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        reply_data = request.data
        reply_data['user_id'] = user_id
        reply_type = reply_data['type']
        with transaction.atomic():
            save_id = transaction.savepoint()
            ser_reply = ReplyQuestionSerializer(data=reply_data)
            if ser_reply.is_valid():
                ser_reply.save()
            question = Question.objects.get(id=reply_data['problem'])
            if reply_type == 2:
                question.reply = question.reply + 1
                question.replyname = user.username
                question.replytime = date.today()
                question.save()
            transaction.savepoint_commit(save_id)
        return Response({'message':'回答成功', 'success':True})

    # 4.11 回答有用
    @action(methods=['put'], detail=True)
    def useful(self, request, pk=None):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        reply = Reply.objects.get(id=pk)
        question_id = reply.problem_id
        reply = Reply.objects.filter(parent_id=pk).filter(user_id=user_id).filter(type=4).\
            filter(Q(useful_count__gt=0) | (Q(unuseful_count__gt=0)))
        if reply.exists():
            return Response({'message': '请不要重复操作', 'success':False})
        else:
            with transaction.atomic():
                save_id = transaction.savepoint()
                reply = Reply.objects.get(id=pk)
                reply.useful_count = reply.useful_count + 1
                reply.save()
                reply = Reply.objects.create(
                    parent_id=pk,
                    user_id=user_id,
                    useful_count=1,
                    type=4,
                    problem_id=question_id,
                )

                transaction.savepoint_commit(save_id)

            return Response({'message': '操作成功', 'success':True})

    # 4.12 回答没用
    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk=None):
        token = request.META.get('HTTP_AUTHORIZATION')[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        reply = Reply.objects.get(id=pk)
        question_id = reply.problem_id
        reply = Reply.objects.filter(parent_id=pk).filter(user_id=user_id).filter(type=4). \
            filter(Q(useful_count__gt=0) | (Q(unuseful_count__gt=0)))
        if reply.exists():
            return Response({'message': '请不要重复操作', 'success':False})
        else:
            with transaction.atomic():
                save_id = transaction.savepoint()
                reply = Reply.objects.get(id=pk)
                reply.unuseful_count = reply.unuseful_count + 1
                reply.save()
                reply = Reply.objects.create(
                    parent_id=pk,
                    user_id=user_id,
                    unuseful_count=1,
                    type=4,
                    problem_id=question_id,
                )
                transaction.savepoint_commit(save_id)

            return Response({'message': '操作成功', 'success':True})


# 登录救急
# class LoginView(View):
#     def post(self, request):
#         user = User.objects.get(id=1)
#         token =Token.objects.create(user=user)
#         return JsonResponse({
#             'mobile': user.mobile,
#             'id': user.id,
#             'token': token.key,
#             'avatar': user.avatar,
#             'username': user.username,
#             'code': 0
#         })
